package searcher.gui;

import java.awt.Color;
import java.util.regex.Pattern;

import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;

/**
 * The PatternTester class is a JFrame extension that easily tests character
 * sequences against patterns.
 * 
 * @version $Id: $
 */
public class PatternTester extends javax.swing.JFrame
{
	JTextField thePatternField;

	JTextField theTestField;

	JTextArea theResultsArea;

	private Pattern thePattern;

	/**
	 * Creates a new (invisible) PatternTester
	 * 
	 */
	public PatternTester()
	{
		getContentPane().setLayout(
			new javax.swing.BoxLayout(getContentPane(),
				javax.swing.BoxLayout.Y_AXIS));
		thePatternField = new JTextField();
		getContentPane().add(thePatternField);
		thePatternField.getDocument().addDocumentListener(
			new javax.swing.event.DocumentListener()
			{
				public void changedUpdate(DocumentEvent e)
				{
					patternChanged();
				}

				public void insertUpdate(DocumentEvent e)
				{
					patternChanged();
				}

				public void removeUpdate(DocumentEvent e)
				{
					patternChanged();
				}
			});
		theTestField = new JTextField();
		getContentPane().add(theTestField);
		theTestField.getDocument().addDocumentListener(
			new javax.swing.event.DocumentListener()
			{
				public void changedUpdate(DocumentEvent e)
				{
					doTest();
				}

				public void insertUpdate(DocumentEvent e)
				{
					doTest();
				}

				public void removeUpdate(DocumentEvent e)
				{
					doTest();
				}
			});
		theResultsArea = new JTextArea();
		theResultsArea.setEditable(false);
		theResultsArea.setPreferredSize(new java.awt.Dimension(400, 300));
		getContentPane().add(theResultsArea);
		pack();
	}

	void patternChanged()
	{
		try
		{
			thePattern = Pattern.compile(thePatternField.getText());
			thePatternField.setBackground(Color.WHITE);
		} catch(Exception e)
		{
			thePatternField.setBackground(Color.RED);
			thePattern = null;
		}
		doTest();
	}

	void doTest()
	{
		theResultsArea.setText("");
		if(thePattern == null || theTestField.getText().length() == 0)
			return;
		java.util.regex.Matcher m = thePattern.matcher(theTestField.getText());
		if(m.find())
		{
			theResultsArea.append("" + m.start());
			while(m.find())
				theResultsArea.append(", " + m.start());
			theResultsArea.append("\n");
		}
		boolean matches = m.matches();
		theResultsArea.append("matches=" + matches + "\n");
		if(matches)
		{
			for(int i = 1; i <= m.groupCount(); i++)
				theResultsArea.append("Group " + i + " = " + m.group(i) + "\n");
		}
	}

	/**
	 * Shows a PatternTester on the screen
	 * 
	 * @param args Command line arguments--ignored
	 */
	public static void main(String [] args)
	{
		new PatternTester().setVisible(true);
	}
}
